package com.wjm.blog.common.util;

import javax.servlet.http.HttpServletRequest;

/**
 * IP工具类
 *
 * @author Ailos
 * @version 1.0
 * @date 2021/4/4 14:51
 */
public class IpUtil {
    private final static String UNKNOWN = "unknown";

    /**
     * 获取客户端IP
     *
     * @param request 客户端请求
     * @return 客户端IP
     * @author: Ailos
     * @version: 1.0
     * @date: 2021/4/4 14:51
     */
    public static String getIp(HttpServletRequest request) throws Exception {
        //获取IP
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String[] ips = ip.split(",");
        return ips[0];
    }

}
